package com.eairlv.utils.config;

import com.eairlv.utils.MSInterceptorProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author eairlv
 * @description
 * @date 10:02 2019/9/5
 */
@WebFilter(urlPatterns = "/*", filterName = "MSFilter")
public class MSFilter implements Filter {

    private static String[] pattern;
    private static final AntPathMatcher MATCHER = new AntPathMatcher();

    @Autowired
    public MSFilter(MSInterceptorProperties msInterceptorProperties){
        pattern = msInterceptorProperties.getRefuse().split(",");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 过滤器主动拦截
        if (pattern != null){
            if (!match((HttpServletRequest) request)){
                chain.doFilter(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    }

    /**
     * URI匹配
     * @param request
     * @return
     */
    private Boolean match(HttpServletRequest request) {
        boolean refuse = Boolean.FALSE;
        String uri = request.getRequestURI();
        for (String s : pattern) {
            if (MATCHER.match(s, uri)) {
                refuse = Boolean.TRUE;
                break;
            }
        }
        return refuse;
    }
}
